// pages/address/address.ts
import api from "../../utils/api"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasAddress:true as boolean,
    addressList:[] as AddressModel[],
    type:'' as string,//跳转过来的类型，add--样本选择地址，order-订单选择地址
  },
  // 添加地HI
  toAddAddress(): void {
    wx.navigateTo({
      url:"/pages/addressInfo/addressInfo"
    })
  },
  // 样本寄回跳过来选择地址
  chooseAddress(e:any): void {
    if(this.data.type == "add") {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.setData({
        chooseAddress: true,
        addressInfo: e.currentTarget.dataset.item
      })
      wx.navigateBack();
    }else if(this.data.type == "order") {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.data.previewInfo.address = e.currentTarget.dataset.item
      prevPage.setData({
        previewInfo:prevPage.data.previewInfo
      })
      prevPage.previewOrder();
      wx.navigateBack();
    }
  },
  // 删除地址
  deleteAddress(e: any): void {
    const that = this
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: "删除",
      content:"确认删除吗？",
      success (res) {
        if (res.confirm) {
          api.address.deleteAddress({id}).then(result => {
            if(result.data.code == "000") {
              wx.showToast({
                title:"删除成功",
                icon:"success",
                duration: 2000
              })
              that.getAddressList();
            }else {
              wx.showToast({
                title: result.data.message as string,
                icon:"error",
                duration: 2000
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 去编辑地址页面
  toEditAddress(e:any): void {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url:"/pages/addressInfo/addressInfo?id=" + id
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options:any) {
    this.setData({
      type: options.type
    })
  },
  getAddressList(): void {
    api.address.getAddressList().then(res => {
      if(res.data.code == "000") {
        this.setData({
          addressList:res.data.data
        })
      }else {
        wx.showToast({
          title: res.data.message as string,
          icon:"error",
          duration: 2000
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddressList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})